<?php


namespace app\app\controller\sys;

use app\common\Page;
use app\model\UserModel;
use app\model\UserRoleModel;
use think\facade\Db;
use support\Request;
use app\services\Permission;

class User
{
    protected $app_id = 0;

    public function beforeAction(Request $request){
        $this->app_id = $request->app_id;
    }

    /**
     * @Permission(action="sys:user:lst")
     */
    public function lst(){
        $userModel = new UserModel();
        $where=[['deleted','=',0]];
        if (input('username')){
            $where[]=['username','=',input('username')];
        }
        if (input('realname')){
            $where[]=['realname','=',input('realname')];
        }
        $count = $userModel->where($where)->count();
        $page = new Page($count,input('limit'),input('page'));
        $ulst = $userModel::with(['dept','position','roles'])->where($where)->limit($page->firstRow , $page->listRows)->select();
        $return['data'] = $ulst;
        $return['page']['page'] = input('page');
        $return['page']['limit'] = input('limit');
        $return['page']['count'] = $count;
        return success($return);
    }

    /**
     * @Permission(action="sys:user:add")
     */
    public function add(){
        $userModel = new UserModel();
        $userRoleModel = new UserRoleModel();
        $_user = json_decode(input('user'), true);
        $_roleIds = $_user['roleIds'] ?? [];
        unset($_user['roleIds']);
        $_user['app_id']=$this->app_id;
        $_user['add_time']=time();
        $_user['password']=md5($_user['password']);
        $_user['update_timestamp']=time();
        $_user['logout_timestamp']=time();
        Db::startTrans();// 启动事务
        try {
            $res = $userModel->insertGetId($_user);//新增数据并返回主键值
            foreach($_roleIds as $r){
                $userRoleModel::create(['user_id'=>$res,'role_id'=>$r,'add_time'=>time()]);
            }
            Db::commit();// 提交事务
            return success(null,0,"添加成功");
        } catch (\Exception $e) {
            Db::rollback();// 回滚事务
            return error(1,"添加失败");
        }
    }

    /**
     * @Permission(action="sys:user:edt")
     */
    public function edt(){
        $userModel = new UserModel();
        $userRoleModel = new UserRoleModel();
        $_user = json_decode(input('user'), true);
        $_roleIds = $_user['roleIds'] ?? [];
        unset($_user['roleIds'],$_user['pivot'],$_user['roles'],$_user['dept_name'],$_user['position_name']);
        $_user['update_timestamp']=time();
        Db::startTrans();// 启动事务
        try {
            $userModel::update($_user);//新增数据并返回主键值
            $userRoleModel->where([['user_id','=',$_user['user_id']]])->delete();
            foreach($_roleIds as $r){
                $userRoleModel::create(['user_id'=>$_user['user_id'],'role_id'=>$r,'add_time'=>time()]);
            }
            Db::commit();// 提交事务
            return success(null,0,"修改成功");
        } catch (\Exception $e) {
            Db::rollback();// 回滚事务
            return error(1,"修改失败");
        }
    }

    /**
     * @Permission(action="sys:user:edt")
     */
    public function set(){
        $_user_id = input('user_id');
        $userModel = new UserModel();
        $where[]=['user_id','in',strval($_user_id)];
        $res = $userModel->where($where)->update([input('field')=>input('val')]);
        return $res ? success(null,0,"修改成功") : error(1,"修改失败");
    }

    /**
     * @Permission(action="sys:user:del")
     */
    public function del(){
        $_user_id = input('user_id');
        $where[]=['user_id','in',strval($_user_id)];
        $res = UserModel::where($where)->update(["deleted"=>1]);
        return $res ? success(null,0,"删除成功") : error(1,"删除失败");
    }
}